package com.platform.qujia.controller;

import java.util.List;
import java.util.Date;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import com.yunhua.oil.common.core.utils.LocalDateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import com.platform.qujia.utils.weixinapp.WeiXinUserUtil;
import com.platform.qujia.utils.weixinapp.WxActivateMemberCard;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

/*
 * <Title> WeiXinCardController </Title>
 * <Description> 微信卡券 </Description>
 * @Date 2021年12月3日
 */
@RestController
@Api(tags = "微信卡券")
@Slf4j
public class WeiXinCardController {

    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Autowired
    private IdempotentUtil idempotentUtil;

    @Value("${domain.adminName}")
    private String adminName;


    @Resource
    private CouponService couponService;

    @Resource
    private CouponController couponController;

    @Resource
    private RegistrationReleaseService registrationReleaseService;
    @Autowired
    private IUserRecommendRecordService userRecommendRecordService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserInviteInfoService sysUserInviteInfoService;

    @Resource
    private WeChatService weChatService;


    /**
     * 手动清除缓存accesToken
     *
     * @return
     */
    @GetMapping("/delAccessTokenToRedis")
    public String delAccessTokenToRedis(@RequestParam String appId) {
        ResultData resultData = null;    //返回结果
        if (redisCacheUtil.hasKey("access_token_" + appId)) {
            log.info("access_token_" + appId + "的access_token信息: " + redisCacheUtil.getCacheObject("access_token_" + appId));
            boolean b = redisCacheUtil.deleteObject("access_token_" + appId);
            log.info("是否已删除boolean值: " + b);
            if (b) {
                resultData = ResultData.success(CodeMsg.SUCCESS);
            }
        } else {
            resultData = ResultData.success("暂无此 " + appId + "的accessToken");
        }
        return new Gson().toJson(resultData);
    }


//    @ApiOperation(value = "getJeRedis")
//    @GetMapping("/getJeRedis")
//    public String getJeRedis(@RequestParam String appId){
//        ResultData resultData =null;    //返回结果
//        resultData = ResultData.success(redisCacheUtil.getCacheObject("wx:access_token:" + appId));
//        return new Gson().toJson(resultData);
//    }

    /**
     * SaaS系统获取accessToken
     *
     * @return
     */
    @ApiOperation(value = "SaaS系统获取accessToken")
    @PostMapping("/getAccessTokenFromSaas")
    public String getAccessTokenFromSaas(@RequestBody WxAppInfo wxAppInfo) {
        log.info("进来了token--------------------------------");
        ResultData resultData = null;    //返回结果null-----------AppSecret---------------------
        if (StringUtils.isNotBlank(wxAppInfo.getAppId())) {
            log.info(wxAppInfo.getAppSecret() + "-----------AppSecret---------------------");
//            if (wxAppInfo.getAppSecret().equals("null")){
//                log.info("null--------------------------------");
//                wxAppInfo.setAppSecret(null);
//            }
            resultData = ResultData.success(this.getTokenByRedisCache(wxAppInfo.getAppId(), wxAppInfo.getAppSecret()));
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return new Gson().toJson(resultData);
    }

    /**
     * 微信卡券获取地址url
     *
     * @param enterpriseId
     * @param outStr
     * @return
     */
    @GetMapping("/getCardUrl")
    @ApiOperation(value = "获取微信卡券网址")
    public String getCardUrl(@RequestParam Integer enterpriseId, @RequestParam String outStr, @RequestParam String openId, Integer shareUserId, Long inviteUserId) {
        log.info("getCardUrl 前端传入参数: 油企ID：" + enterpriseId + "； 随机字符串：" + outStr + "； openId: " + openId + "；分享者shareUserId：" + shareUserId + "；推荐员工id inviteUserId：" + inviteUserId);
        String key = IdempotentUtil.GenerateKey("getCardUrl", String.valueOf(enterpriseId), openId);
        if (!idempotentUtil.tryLock(key)) {
            log.error("/getCardUrl接口频繁请求，time:{}", System.currentTimeMillis());
            return ResultData.errorJson("request frequently");
        }
        ResultData resultData = null;    //返回结果
        Map<String, Object> resultMap = new HashMap<>();
        //获取用户是否已激活
        AppUserInfo appUserInfo =
                appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                        .stationId(enterpriseId)
                        .blogOpenid(openId).build());
        log.info("获取用户信息appUserInfo: " + appUserInfo);
        if (null != appUserInfo && StringUtils.isNotBlank(appUserInfo.getCardCode())) {
            log.info("cardCode: " + appUserInfo.getCardCode());
            resultMap.put("mobilePhone", appUserInfo.getMobilePhone());
            resultMap.put("unionId", appUserInfo.getUnionId());
            //resultMap.put("consumerId",appUserInfo.getUserId());
            resultData = ResultData.success(resultMap);
        } else {
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            if (null != enterprise) {
                log.info("油企信息,enterpriseId:[{}],cardId:[{}]", enterpriseId, enterprise.getCardId());
                Map<String, Object> map = new HashMap();
                map.put("openid", openId);
                map.put("card_id", enterprise.getCardId());
                String accessToken = this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret());
                //获取用户已开卡的列表 //https://api.weixin.qq.com/card/user/getcardlist?access_token=TOKEN
                JSONObject jsonObjectIsAct = HttpClientUtil.doPostJson(
                        "https://api.weixin.qq.com/card/user/getcardlist?access_token=" + accessToken,
                        JSON.toJSONString(map));
                log.info("第一次卡列表请求,jsonObjectIsAct信息: " + jsonObjectIsAct);
                if (jsonObjectIsAct.containsKey("errcode") && jsonObjectIsAct.get("errcode").toString().equals("40001")) {
                    //如果access_token失效；
                    log.info("token失效，重新获取token");
                    boolean b = redisCacheUtil.deleteObject("access_token_" + enterprise.getGzhAppId());
                    if (b)
                        accessToken = this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret());
                    jsonObjectIsAct = HttpClientUtil.doPostJson(
                            "https://api.weixin.qq.com/card/user/getcardlist?access_token=" + accessToken,
                            JSON.toJSONString(new HashMap<String, Object>() {{
                                this.put("openid", openId);
                                this.put("card_id", enterprise.getCardId());
                            }}));
                    log.info("第二次卡列表请求,jsonObjectIsAct信息: " + jsonObjectIsAct);
                }
                if (jsonObjectIsAct.containsKey("card_list")) {
                    List<Map<String, Object>> cardList = (List<Map<String, Object>>) jsonObjectIsAct.get("card_list");
                    if (cardList != null && cardList.size() > 0) {
                        String code = "";
                        for (Map m : cardList) {
                            if (StringUtils.equals(enterprise.getCardId(), m.get("card_id").toString())) {
                                code = m.get("code").toString();
                                break;
                            }
                        }
                        if (StringUtils.isNotBlank(code)) {
                            Map<String, Object> maps = new HashMap<>();
                            maps.put("card_id", enterprise.getCardId());
                            maps.put("code", code);
                            //激活后获取卡信息
                            JSONObject jsonWxMemberCardInfo =
                                    HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" + accessToken,
                                            JSON.toJSONString(maps));
                            log.info("第一次,jsonWxMemberCardInfo信息: " + jsonWxMemberCardInfo);
                            if (jsonWxMemberCardInfo.containsKey("errcode") && jsonWxMemberCardInfo.get("errcode").toString().equals("40001")) {
                                log.info("token失效，重新获取token");
                                boolean b = redisCacheUtil.deleteObject("access_token_" + enterprise.getGzhAppId());
                                if (b) {
                                    accessToken = this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret());
                                }
                                jsonWxMemberCardInfo = HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" + accessToken, JSON.toJSONString(map));
                                log.info("第二次,jsonWxMemberCardInfo信息: " + jsonWxMemberCardInfo);
                            }
                            //如果已激活
                            if ("true".equals(jsonWxMemberCardInfo.get("has_active").toString())) {
                                if (jsonWxMemberCardInfo.containsKey("user_info")) {
                                    String mobilePhone = ""; //手机号
                                    String sex = "";         //性别
                                    String nickname = "";    //昵称
                                    //3、读取手机号
                                    Map<String, Object> mapPhone = JSON.parseObject(jsonWxMemberCardInfo.get("user_info").toString(), Map.class);
                                    List<Map<String, Object>> commonFieldList = (List<Map<String, Object>>) mapPhone.get("common_field_list");
                                    log.info("commonFieldList: " + commonFieldList);
                                    if (null != commonFieldList && commonFieldList.size() > 0) {
                                        for (Map<String, Object> m : commonFieldList) {
                                            if ("USER_FORM_INFO_FLAG_MOBILE".equals(m.get("name").toString())) {
                                                mobilePhone = m.get("value").toString();
                                                break;
                                            }
                                        }
                                        log.info("openid:[{}],手机号:[{}]", openId, mobilePhone);
                                        if (StringUtils.isNotBlank(mobilePhone)) {
                                            if (jsonWxMemberCardInfo.containsKey("sex"))
                                                sex = "MALE".equals(jsonWxMemberCardInfo.get("sex").toString()) ? "2" : "1";
                                            if (jsonWxMemberCardInfo.containsKey("nickname"))
                                                nickname = jsonWxMemberCardInfo.get("nickname").toString();
                                            //更新用户信息： 昵称 手机号 性别
                                            AppUserInfo userInfo = this.updateAppUserInfo(enterpriseId, openId, mobilePhone, sex, nickname, code, shareUserId, inviteUserId);
//                                            this.updateAppUserInfo(AppUserInfo.builder()
//                                                    .stationId(enterprise.getEnterpriseId())
//                                                    .blogOpenid(openId)
//                                                    .blogNickName(nickname)
//                                                    .sex(sex)
//                                                    .mobilePhone(mobilePhone)
//                                                    .registeDate(new Date())
//                                                    .balance(BigDecimal.ZERO)
//                                                    .growUpValue(0)
//                                                    .integral(0)
//                                                    .followStatus("1")
//                                                    .memberCode(new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5))  //会员编号
//                                                    .cardCode(code)      //卡的code
//                                                    .build(), shareUserId);
                                            //返回前端结果
                                            resultMap.put("mobilePhone", mobilePhone);
                                            resultMap.put("nickName", nickname);
                                            //resultMap.put("consumerId",userInfo.getUserId());
                                            resultMap.put("sex", sex);
                                            log.info("getCardUrl前端返回,mobilePhone:[{}],nickName:[{}],sex:[{}]", mobilePhone, nickname, sex);
                                            resultData = ResultData.success(resultMap);
                                        } else {
                                            resultData = ResultData.error(CodeMsg.USER_FORM_INFO_FLAG_MOBILE_ERROR, jsonWxMemberCardInfo.toString());
                                        }
                                    } else {
                                        resultData = ResultData.error(CodeMsg.COMMON_FIELD_LIST_ERROR, jsonWxMemberCardInfo.toString());
                                    }
                                } else {
                                    resultData = ResultData.error(CodeMsg.MEMBERCARD_INFO_NOT_EXIST, jsonWxMemberCardInfo.toString());
                                }
                            } else {
                                //未激活 不存在，则前去请求微信获取url
                                JSONObject jsonObject = HttpClientUtil.doPostJson(
                                        "https://api.weixin.qq.com/card/membercard/activate/geturl?access_token=" + accessToken,
                                        JSON.toJSONString(new HashMap<String, Object>() {{
                                            this.put("card_id", enterprise.getCardId());
                                            this.put("outer_str", outStr);
                                        }}));
                                log.info("getCardUrl前端跳转,微信返回:{}", jsonObject);
                                resultData = ResultData.success(jsonObject);
                            }
                        } else {
                            //未激活 不存在，则前去请求微信获取url
                            JSONObject jsonObject = HttpClientUtil.doPostJson(
                                    "https://api.weixin.qq.com/card/membercard/activate/geturl?access_token=" + accessToken,
                                    JSON.toJSONString(new HashMap<String, Object>() {{
                                        this.put("card_id", enterprise.getCardId());
                                        this.put("outer_str", outStr);
                                    }}));
                            log.info("getCardUrl前端跳转,微信返回:{}", jsonObject);
                            resultData = ResultData.success(jsonObject);
                        }
                    } else {
                        //未激活 不存在，则前去请求微信获取url
                        JSONObject jsonObject = HttpClientUtil.doPostJson(
                                "https://api.weixin.qq.com/card/membercard/activate/geturl?access_token=" + accessToken,
                                JSON.toJSONString(new HashMap<String, Object>() {{
                                    this.put("card_id", enterprise.getCardId());
                                    this.put("outer_str", outStr);
                                }}));
                        log.info("getCardUrl前端跳转,微信返回:{}", jsonObject);
                        resultData = ResultData.success(jsonObject);
                    }
                } else {
                    //未激活 不存在，则前去请求微信获取url
                    JSONObject jsonObject = HttpClientUtil.doPostJson(
                            "https://api.weixin.qq.com/card/membercard/activate/geturl?access_token=" + accessToken,
                            JSON.toJSONString(new HashMap<String, Object>() {{
                                this.put("card_id", enterprise.getCardId());
                                this.put("outer_str", outStr);
                            }}));
                    log.info("getCardUrl前端跳转,微信返回:{}", jsonObject);
                    resultData = ResultData.success(jsonObject);
                }
            } else {
                log.info("油企未找到:{}", enterpriseId);
                resultData = ResultData.error(CodeMsg.ENTERPRISE_NULL_INFO);
            }
        }
        idempotentUtil.releaseLock(key);
        return new Gson().toJson(resultData);
    }

    /***
     * 根据微信卡券ID查询油企信息
     * @param cardId
     * @return
     */
    @GetMapping("/selectEnterpriseIdByCardId")
    @ApiOperation(value = "根据微信cardId 获取油企信息")
    public String selectEnterpriseIdByCardId(@RequestParam String cardId) {
        ResultData resultData = null;
        Enterprise enterprise = enterpriseService.selectEnterpriseByCardId(cardId);
        if (enterprise != null) {
            resultData = ResultData.success(enterprise.getEnterpriseId());
        } else {
            resultData = ResultData.error(CodeMsg.NO_CARD_ID_ENTERPRISE);
        }
        return new Gson().toJson(resultData);
    }

//    @Value("")
//    private String  str;
//    @PostMapping("/selectTest")
//    public void test(){
//        log.info("哈哈"+ YmlConfig.getCardId());
//        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(72);
//        log.info(enterprise.getCardId());
//        log.info("222");
//    }

    /**
     * 获取卡手机号
     *
     * @param wcp
     * @return
     */
    @PostMapping("/selectCardMobilePhone")
    @ApiOperation(value = "获取微信卡券手机号")
    @Transactional(rollbackFor = Exception.class)
    public String selectCardMobilePhone(@RequestBody WxCardInfoParm wcp) {
        ResultData resultData = null;
        log.info("selectCardMobilePhone前端传入的参数：" + wcp.toString());
        String key = IdempotentUtil.GenerateKey("selectCardMobilePhone", String.valueOf(wcp.getEnterpriseId()), wcp.getOpenId());
        if (!idempotentUtil.tryLock(key)) {
            log.error("/selectCardMobilePhone接口频繁请求，time:{}", System.currentTimeMillis());
            return ResultData.errorJson("request frequently");
        }
        Map<String, Object> resultMap = new HashMap<>();
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(wcp.getEnterpriseId());
        String accessToken = this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret());
        String mobilePhone = "";
        //1、获取用户开卡时提交的信息（跳转型开卡组件）
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("activate_ticket", wcp.getActivateTicket());
        log.info("activate_ticket: " + stringObjectHashMap);
        JSONObject jsonWxCardInfo =
                HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/membercard/activatetempinfo/get?access_token=" + accessToken,
                        JSON.toJSONString(stringObjectHashMap));
        log.info("获取用户开卡时提交的信息jsonWxCardInfo：" + jsonWxCardInfo);
        if ("0".equals(jsonWxCardInfo.get("errcode").toString())) {

            //2、读取手机号
            Map<String, Object> map = JSON.parseObject(jsonWxCardInfo.get("info").toString(), Map.class);
            List<Map<String, Object>> commonFieldList = (List<Map<String, Object>>) map.get("common_field_list");
            log.info("commonFieldList: " + commonFieldList);
            if (null != commonFieldList && commonFieldList.size() > 0) {
                for (Map<String, Object> m : commonFieldList) {
                    if ("USER_FORM_INFO_FLAG_MOBILE".equals(m.get("name").toString())) {
                        mobilePhone = m.get("value").toString();
                        break;
                    }
                }
                if (StringUtils.isNotBlank(mobilePhone)) {
                    //3、解密encrypt_code 获取code激活
                    JSONObject jsonCode =
                            HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/code/decrypt?access_token=" + accessToken,
                                    JSON.toJSONString(new HashMap<String, Object>() {{
                                        this.put("encrypt_code", wcp.getEncryptCode());
                                    }}));
                    log.info("获取Code：" + jsonCode);
                    if ("0".equals(jsonCode.get("errcode").toString())) {
                        //4、获取系统内用户信息
                        AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().stationId(enterprise.getEnterpriseId()).blogOpenid(wcp.getOpenId()).build());
                        if (null != appUserInfo) {
                            //更新
                            appUserInfoService.updateAppUserInfo(AppUserInfo.builder()
                                    .stationId(enterprise.getEnterpriseId())
                                    .blogOpenid(wcp.getOpenId())
                                    .mobilePhone(mobilePhone)
                                    .cardCode(jsonCode.get("code").toString())
                                    .build());
                        } else {
                            //新增
                            appUserInfoService.addAppUserInfo(AppUserInfo.builder()
                                    .stationId(enterprise.getEnterpriseId())
                                    .blogOpenid(wcp.getOpenId())
                                    .mobilePhone(mobilePhone)
                                    .registeDate(new Date())
                                    .balance(BigDecimal.ZERO)
                                    .growUpValue(0)
                                    .integral(0)
                                    .followStatus("1")
//                                    .memberCode(new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5))  //会员编号
                                    .cardCode(jsonCode.get("code").toString())      //卡的code
                                    .build());
                        }

                        //5、获取要激活的card信息
                        JSONObject jsonCardInfoToActivate =
                                HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/code/get?access_token=" + accessToken,
                                        JSON.toJSONString(new HashMap<String, Object>() {{
                                            this.put("card_id", enterprise.getCardId());
                                            this.put("code", jsonCode.getString("code"));
                                        }}));
                        log.info("要激活card的信息：" + jsonCardInfoToActivate);
                        if ("0".equals(jsonCardInfoToActivate.get("errcode").toString())) {
                            //6、激活卡券
                            Map<String, Object> activateMap = JSON.parseObject(jsonCardInfoToActivate.get("card").toString(), Map.class);
                            JSONObject jsonCardActResult = HttpClientUtil.doPostJson(
                                    "https://api.weixin.qq.com/card/membercard/activate?access_token=" + accessToken,
                                    JSON.toJSONString(WxActivateMemberCard.builder()
                                            .card_id(activateMap.get("card_id").toString())
                                            .code(activateMap.get("code").toString())
                                            .init_bonus("0")
                                            .init_bonus_record("创建会员卡")
                                            .membership_number(activateMap.get("membership_number").toString())
                                            //.init_custom_field_value1(wac.getInit_custom_field_value1())
                                            //.init_balance(wac.getInit_balance())
                                            //.background_pic_url(wac.getBackground_pic_url())
                                            .build()));
                            log.info("卡激活结果：" + jsonCardActResult);
                            //激活成功
                            if ("0".equals(jsonCardActResult.get("errcode").toString())) {
                                resultMap.put("mobilePhone", mobilePhone);
                                if (jsonCardInfoToActivate.containsKey("unionid")) {
                                    resultMap.put("unionId", jsonCardInfoToActivate.get("unionid").toString());
                                }
                                resultData = ResultData.success(resultMap);
                            } else {
                                //激活失败，事务回滚
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                //激活卡失败时，微信返回错误信息
                                resultData = ResultData.error(CodeMsg.ACTIVATE_CARD_ERROR, jsonCardActResult.toString());
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.CARD_INFO_TO_ACTIVATE_ERROR, jsonCardInfoToActivate.toString());
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.ENCRYPT_CODE_ERROR, jsonCode.toString());
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.USER_FORM_INFO_FLAG_MOBILE_ERROR, jsonWxCardInfo.toString());
                }
            } else {
                resultData = ResultData.error(CodeMsg.COMMON_FIELD_LIST_ERROR, jsonWxCardInfo.toString());
            }
        } else {
            resultData = ResultData.error(CodeMsg.ACTIVATE_TICKET_ERROR, jsonWxCardInfo.toString());
        }
        log.info("返回前端结果：" + resultData.getData() + " ; 业务码retCode: " + resultData.getRetCode());
        idempotentUtil.releaseLock(key);
        return new Gson().toJson(resultData);
    }

    /************************************************************************************************************************************************************************************************************
     * 根据微信卡券获取微信卡券用户信息:   此方法作用备注：公众号用户卡券直接激活；
     * @param wcp
     * @return
     **********************************************************************************************************************************************************************************************************/
    @PostMapping("/selectWxMemberCardInfo")
    @ApiOperation(value = "获取微信卡券用户信息")
    @Transactional(rollbackFor = Exception.class)
    public String selectWxMemberCardInfo(@RequestBody WxCardInfoParm wcp) {
        ResultData resultData = null;
        log.info("selectWxMemberCardInfo 前端传入的参数：" + wcp.toString());
        String key = IdempotentUtil.GenerateKey("selectWxMemberCardInfo", String.valueOf(wcp.getEnterpriseId()), wcp.getOpenId());
        if (!idempotentUtil.tryLock(key)) {
            log.error("/selectWxMemberCardInfo接口频繁请求，time:{}", System.currentTimeMillis());
            return ResultData.errorJson("request frequently");
        }
        Map<String, Object> resultMap = new HashMap<>();
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(wcp.getEnterpriseId());
        String mobilePhone = ""; //手机号
        String sex = "";         //性别
        String nickname = "";    //昵称
        //1、解密encrypt_code 获取code激活
        JSONObject jsonCode =
                HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/code/decrypt?access_token=" + this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret()),
                        JSON.toJSONString(new HashMap<String, Object>() {{
                            this.put("encrypt_code", wcp.getEncryptCode());
                        }}));
        log.info("获取Code：" + jsonCode);
        if ("0".equals(jsonCode.get("errcode").toString())) {
            //2、获取要激活的card信息
            JSONObject jsonCardInfoToActivate =
                    HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/code/get?access_token=" + this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret()),
                            JSON.toJSONString(new HashMap<String, Object>() {{
                                this.put("card_id", enterprise.getCardId());
                                this.put("code", jsonCode.getString("code"));
                            }}));
            log.info("要激活card的信息：" + jsonCardInfoToActivate);
            if ("0".equals(jsonCardInfoToActivate.get("errcode").toString())) {
                //保存或更新用户信息：用户卡code；
//                this.updateAppUserInfo(AppUserInfo.builder()
//                        .stationId(enterprise.getEnterpriseId())
//                        .blogOpenid(wcp.getOpenId())
//                        .registeDate(new Date())
//                        .balance(BigDecimal.ZERO)
//                        .growUpValue(0)
//                        .integral(0)
//                        .followStatus("1")
//                        .memberCode(new SimpleDateFormat("yyMMdd").format(new Date())+ RandomStringUtils.randomNumeric(5))  //会员编号
//                        .cardCode(jsonCode.get("code").toString())      //卡的code
//                        .build());

                //3、激活卡券
                Map<String, Object> activateMap = JSON.parseObject(jsonCardInfoToActivate.get("card").toString(), Map.class);
                JSONObject jsonCardActResult = HttpClientUtil.doPostJson(
                        "https://api.weixin.qq.com/card/membercard/activate?access_token=" + this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret()),
                        JSON.toJSONString(WxActivateMemberCard.builder()
                                .card_id(activateMap.get("card_id").toString())
                                .code(activateMap.get("code").toString())
                                .init_bonus("0")
                                .init_bonus_record("创建会员卡")
                                .membership_number(activateMap.get("membership_number").toString())
                                //.init_custom_field_value1(wac.getInit_custom_field_value1())
                                //.init_balance(wac.getInit_balance())
                                //.background_pic_url(wac.getBackground_pic_url())
                                .build()));
                log.info("卡激活结果：" + jsonCardActResult);
                if ("0".equals(jsonCardActResult.get("errcode").toString())) {
                    //4、激活后获取卡信息
                    JSONObject jsonWxMemberCardInfo =
                            HttpClientUtil.doPostJson("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" + this.getTokenByRedisCache(enterprise.getGzhAppId(), enterprise.getGzhAppSecret()),
                                    JSON.toJSONString(new HashMap<String, Object>() {{
                                        this.put("card_id", enterprise.getCardId());
                                        this.put("code", jsonCode.get("code").toString());
                                    }}));
                    log.info("获取卡信息jsonWxMemberCardInfo：" + jsonWxMemberCardInfo);
                    if ("true".equals(jsonWxMemberCardInfo.get("has_active").toString())) {
                        if (jsonWxMemberCardInfo.containsKey("user_info")) {
                            //3、读取手机号
                            Map<String, Object> mapPhone = JSON.parseObject(jsonWxMemberCardInfo.get("user_info").toString(), Map.class);
                            List<Map<String, Object>> commonFieldList = (List<Map<String, Object>>) mapPhone.get("common_field_list");
                            log.info("commonFieldList: " + commonFieldList);
                            if (null != commonFieldList && commonFieldList.size() > 0) {
                                for (Map<String, Object> m : commonFieldList) {
                                    if ("USER_FORM_INFO_FLAG_MOBILE".equals(m.get("name").toString())) {
                                        mobilePhone = m.get("value").toString();
                                        break;
                                    }
                                }
                                log.info("手机号：" + mobilePhone);
                                if (StringUtils.isNotBlank(mobilePhone)) {
                                    if (jsonWxMemberCardInfo.containsKey("sex"))
                                        sex = "MALE".equals(jsonWxMemberCardInfo.get("sex").toString()) ? "2" : "1";
                                    if (jsonWxMemberCardInfo.containsKey("nickname"))
                                        nickname = jsonWxMemberCardInfo.get("nickname").toString();
                                    //更新用户信息： 昵称 手机号 性别
                                    AppUserInfo userInfo = this.updateAppUserInfo(enterprise.getEnterpriseId(), wcp.getOpenId(), mobilePhone, sex, nickname, jsonCode.get("code").toString(), wcp.getUserId(), wcp.getInviteUserId());
//                                    this.updateAppUserInfo(AppUserInfo.builder()
//                                            .stationId(enterprise.getEnterpriseId())
//                                            .blogOpenid(wcp.getOpenId())
//                                            .blogNickName(nickname)
//                                            .sex(sex)
//                                            .mobilePhone(mobilePhone)
//                                            .registeDate(new Date())
//                                            .balance(BigDecimal.ZERO)
//                                            .growUpValue(0)
//                                            .integral(0)
//                                            .followStatus("1")
//                                            .memberCode(new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5))  //会员编号
//                                            .cardCode(jsonCode.get("code").toString())      //卡的code
//                                            .build(), wcp.getUserId());
                                    //返回前端结果
                                    resultMap.put("mobilePhone", mobilePhone);
                                    resultMap.put("nickName", nickname);
                                    resultMap.put("sex", sex);
                                    //resultMap.put("consumerId",userInfo.getUserId());
                                    if (jsonCardInfoToActivate.containsKey("unionid")) {
                                        resultMap.put("unionId", jsonCardInfoToActivate.get("unionid").toString());
                                    }
                                    resultData = ResultData.success(resultMap);
                                } else {
                                    resultData = ResultData.error(CodeMsg.USER_FORM_INFO_FLAG_MOBILE_ERROR, jsonWxMemberCardInfo.toString());
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.COMMON_FIELD_LIST_ERROR, jsonWxMemberCardInfo.toString());
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.MEMBERCARD_INFO_NOT_EXIST, jsonWxMemberCardInfo.toString());
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.MEMBERCARD_USER_INFO_ERROR, jsonWxMemberCardInfo.toString());
                    }
                } else {
                    //激活卡失败时，微信返回错误信息
                    resultData = ResultData.error(CodeMsg.ACTIVATE_CARD_ERROR, jsonCardActResult.toString());
                }
            } else {
                //获取激活卡券时所用到卡信息时，微信返回错误信息；
                resultData = ResultData.error(CodeMsg.CARD_INFO_TO_ACTIVATE_ERROR, jsonCardInfoToActivate.toString());
            }
        } else {
            //获取code失败时，微信返回错误信息；
            resultData = ResultData.error(CodeMsg.ENCRYPT_CODE_ERROR, jsonCode.toString());
        }
        idempotentUtil.releaseLock(key);
        return new Gson().toJson(resultData);
    }


    public void updateAppUserInfo(AppUserInfo appUserInfo, Integer userId) {
        //4、获取系统内用户信息
        AppUserInfo appUserInfos = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                .stationId(appUserInfo.getStationId())
                .mobilePhone(appUserInfo.getMobilePhone())
                //.blogOpenid(appUserInfo.getBlogOpenid())
                .build());
        if (null != appUserInfos) {
            //更新
            appUserInfoService.updateAppUserInfo(AppUserInfo.builder()
                    .stationId(appUserInfo.getStationId())
                    .blogOpenid(appUserInfo.getBlogOpenid())
                    .blogNickName(appUserInfo.getBlogNickName())
                    .sex(appUserInfo.getSex())
                    .mobilePhone(appUserInfo.getMobilePhone())
                    .cardCode(appUserInfo.getCardCode())
                    .build());
        } else {
            //新增
            appUserInfoService.addAppUserInfo(AppUserInfo.builder()
                    .stationId(appUserInfo.getStationId())
                    .blogOpenid(appUserInfo.getBlogOpenid())
                    .blogNickName(appUserInfo.getBlogNickName())
                    .sex(appUserInfo.getSex())
                    .mobilePhone(appUserInfo.getMobilePhone())
                    .registeDate(new Date())
                    .balance(BigDecimal.ZERO)
                    .growUpValue(0)
                    .integral(0)
                    .followStatus("1")
//                    .memberCode(new SimpleDateFormat("yyMMdd").format(new Date()) + RandomStringUtils.randomNumeric(5))  //会员编号
                    .cardCode(appUserInfo.getCardCode())      //卡的code
                    .build());

            // userId为推广者id，推广次数+1
            if (ObjectUtils.isNotEmpty(userId)) {
                appUserInfoService.increaseShareCount(Long.valueOf(userId));
            }
        }
    }

    public AppUserInfo updateAppUserInfo(Integer enterpriseId, String openId, String mobilePhone, String sex, String nickname, String code, Integer userId, Long inviteUserId) {
        //获取系统内用户信息
        AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                .stationId(enterpriseId)
                .blogOpenid(openId)
                .build());
        if (appUserInfo != null) {
            if (MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone())) {
                // 之前是游客，查询是不是导入用户
                AppUserInfo importUser = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                        .stationId(enterpriseId)
                        .mobilePhone(mobilePhone)
                        .build());
                if (importUser == null) {
                    // 不是导入用户
                    appUserInfo.setBlogNickName(nickname);
                    appUserInfo.setSex(sex);
                    appUserInfo.setMobilePhone(mobilePhone);
                    appUserInfo.setMemberCode(LocalDateUtils.format(LocalDate.now(), "yyMMdd") + RandomStringUtils.randomNumeric(5));
                    appUserInfo.setCardCode(code);
                    String id = yunHuaPayUtils.sendUser(mobilePhone);
                    if (!"".equals(id)) {
                        appUserInfo.setYunhuaUserId(id);
                    }
                    appUserInfo.setIntegral(MathUtil.add(null, appUserInfo.getIntegral()));
                    appUserInfo.setGrowUpValue(MathUtil.add(null, appUserInfo.getGrowUpValue()));
                    appUserInfoService.updateById(appUserInfo);
                } else {
                    // 有记录
                    if (StringUtils.isNotBlank(importUser.getBlogOpenid())) {
                        throw new CustomException("微信用户已存在");
                    }
                    appUserInfo.setBlogNickName(nickname);
                    appUserInfo.setSex(sex);
                    appUserInfo.setMobilePhone(mobilePhone);
                    appUserInfo.setCardCode(code);
                    mergerUserInfo(appUserInfo, importUser);
                    appUserInfoService.deleteUserInfoById(importUser.getUserId());
                    appUserInfoService.updateById(appUserInfo);
                }
            } else {
                // 老用户
                appUserInfo.setBlogNickName(nickname);
                appUserInfo.setSex(sex);
                //appUserInfo.setMobilePhone(mobilePhone);
                if (StringUtils.isBlank(appUserInfo.getMemberCode())) {
                    appUserInfo.setMemberCode(LocalDateUtils.format(LocalDate.now(), "yyMMdd") + RandomStringUtils.randomNumeric(5));
                }
                appUserInfo.setCardCode(code);
                appUserInfoService.updateById(appUserInfo);
                return appUserInfo;
            }
        } else {
            appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                    .stationId(enterpriseId)
                    .mobilePhone(mobilePhone)
                    .build());
            if (appUserInfo != null) {
                // 导入用户
                appUserInfo.setBlogOpenid(openId);
                appUserInfo.setBlogNickName(nickname);
                appUserInfo.setSex(sex);
                appUserInfo.setMemberCode(LocalDateUtils.format(LocalDate.now(), "yyMMdd") + RandomStringUtils.randomNumeric(5));
                appUserInfo.setCardCode(code);
                String id = yunHuaPayUtils.sendUser(appUserInfo.getMobilePhone());
                if (!"".equals(id)) {
                    appUserInfo.setYunhuaUserId(id);
                }
                appUserInfo.setIntegral(MathUtil.add(null, appUserInfo.getIntegral()));
                appUserInfo.setGrowUpValue(MathUtil.add(null, appUserInfo.getGrowUpValue()));
                if (appUserInfo.getAliUserId() == null || appUserInfo.getAliUserId().equals("")) {
                    appUserInfo.setNumberOfEntry(1);
                }
                appUserInfoService.updateById(appUserInfo);
                //注册发券
                if (appUserInfo.getAliUserId() == null || appUserInfo.getAliUserId().equals("")) {
                    registrationReleaseService.registrationRelease(appUserInfo);
                }
            } else {
                // 新用户
                appUserInfo = new AppUserInfo();
                appUserInfo.setStationId(enterpriseId);
                appUserInfo.setBlogOpenid(openId);
                appUserInfo.setBlogNickName(nickname);
                appUserInfo.setSex(sex);
                appUserInfo.setMobilePhone(mobilePhone);
                appUserInfo.setRegisteDate(new Date());
                appUserInfo.setGrowUpValue(0);
                appUserInfo.setIntegral(0);
                appUserInfo.setFollowStatus("1");
//                appUserInfo.setMemberCode(LocalDateUtils.format(LocalDate.now(),"yyMMdd")+RandomStringUtils.randomNumeric(5));
                appUserInfo.setCardCode(code);
                appUserInfo.setNumberOfEntry(1);
                appUserInfoService.addAppUserInfo(appUserInfo);

                // 记录员工推荐信息
                try {
                    if (null != inviteUserId) {
                        AppUserInfo whereis = new AppUserInfo();
                        whereis.setStationId(enterpriseId);
                        whereis.setBlogOpenid(openId);
                        whereis.setMobilePhone(mobilePhone);
                        AppUserInfo user = appUserInfoService.getAppUserInfo(whereis);
                        SysUserInviteInfo sysUserInviteInfo = new SysUserInviteInfo();
                        sysUserInviteInfo.setAppUserId(user.getUserId().longValue());
                        sysUserInviteInfo.setAppUserPhone(mobilePhone);
                        sysUserInviteInfo.setSysUserId(inviteUserId);
                        sysUserInviteInfo.setStatus("1");
                        sysUserInviteInfo.setCreatedTime(new Date());
                        sysUserInviteInfo.setInviteSuccessTime(appUserInfo.getRegisteDate());
                        sysUserInviteInfoService.addSysUserInviteInfo(sysUserInviteInfo);
                    }
                } catch (Exception ex) {
                    log.error("记录推荐的员工信息失败,inviteUserId：" + inviteUserId);
                    log.error("记录推荐的员工信息失败,异常信息：" + ex.getMessage());
                }

                //注册发券
                registrationReleaseService.registrationRelease(appUserInfo);
                // userId为推广者id，推广次数+1
                if (ObjectUtils.isNotEmpty(userId)) {
                    appUserInfoService.increaseShareCount(Long.valueOf(userId));
                    userRecommendRecordService.insertRecommendRecordAndSendCoupons(userId, appUserInfo);
                }
            }
        }
        return appUserInfo;
    }

    private void mergerUserInfo(AppUserInfo newUser, AppUserInfo oldUser) {
        newUser.setUserType(oldUser.getUserType());
        newUser.setMinaOpenid(oldUser.getMinaOpenid());
        newUser.setGradeName(oldUser.getGradeName());
        newUser.setSexFlag(oldUser.getSexFlag());
        newUser.setRegisteDate(oldUser.getRegisteDate());

        newUser.setUpdateDate(oldUser.getUpdateDate());
        newUser.setUnionId(oldUser.getUnionId());

        newUser.setSource(oldUser.getSource());
        newUser.setName(oldUser.getName());

        newUser.setBirthday(oldUser.getBirthday());

        newUser.setTruckNumber(oldUser.getTruckNumber());
        newUser.setICCard(oldUser.getICCard());

        newUser.setRegisterTime(oldUser.getRegisterTime());
        newUser.setFollowStatus(oldUser.getFollowStatus());
        newUser.setFirstStationId(oldUser.getFirstStationId());
        newUser.setRegisterStationId(oldUser.getRegisterStationId());
        newUser.setTruckBrand(oldUser.getTruckBrand());
        newUser.setUserLevel(oldUser.getUserLevel());


        String memberCode;
        if (StringUtils.isNotBlank(oldUser.getMemberCode())) {
            memberCode = oldUser.getMemberCode();
        } else {
            memberCode = LocalDateUtils.format(LocalDate.now(), "yyMMdd") + RandomStringUtils.randomNumeric(5);
        }
        newUser.setMemberCode(memberCode);
        String yunhuaId;
        if (StringUtils.isNotBlank(oldUser.getYunhuaUserId())) {
            yunhuaId = oldUser.getYunhuaUserId();
        } else {
            yunhuaId = yunHuaPayUtils.sendUser(newUser.getMobilePhone());
            if ("".equals(yunhuaId)) {
                yunhuaId = null;
            }
        }
        newUser.setYunhuaUserId(yunhuaId);
        newUser.setIntegral(MathUtil.add(newUser.getIntegral(), oldUser.getIntegral()));
        newUser.setGrowUpValue(MathUtil.add(newUser.getGrowUpValue(), oldUser.getGrowUpValue()));
    }


    /**
     * 从Redis缓存中获取 tokenCache
     *
     * @param appId
     * @param appSecret
     * @return
     */
    private synchronized String getTokenByRedisCache(String appId, String appSecret) {
        //redis缓存key
        String accessTokenKey = "access_token_" + appId;
        if (!redisCacheUtil.hasKey(accessTokenKey) || redisCacheUtil.getCacheObject(accessTokenKey) == null || redisCacheUtil.getCacheObject(accessTokenKey).equals("")) {
            String token;
            if (Objects.isNull(appSecret)) {
                log.info("开始调用第三方平台token");
                RestTemplate restTemplate = new RestTemplate();
                token = restTemplate.getForObject(adminName + "/prod-api/thirdParty/weChat/getAccessToken?authorizerAppid=" + appId, String.class);
                if (token == null || token.contains("\"code\":500")) {
                    log.error("调用第三方平台token失败，appId:[{}],msg:{}", appId, token);
                    throw new CustomException(CodeMsg.THIRD_PART_AUTHORIZE_FAIL);
                }
                log.info("第三放平台token" + token);
            } else {
                log.info("之前逻辑token");
                token = WeiXinUserUtil.getToken(appId, appSecret).getAccessToken();
            }
//            String token =HttpRequestUtil.getAcccessTokenHttpsRequestData(tokenHttp,"post","{"+appId+"}");
            redisCacheUtil.setCacheObject(accessTokenKey, token);
            redisCacheUtil.expire(accessTokenKey, 7100, TimeUnit.SECONDS);
            log.info("设置Redis缓存中" + appId + "的token信息: " + token);
            return token;
        } else {
            String cacheToken = redisCacheUtil.getCacheObject(accessTokenKey);
            log.info("Redis缓存中" + appId + "的token信息: " + cacheToken);
            return cacheToken;
        }
    }


//    @Async
//    public void registrationRelease(AppUserInfo appUserInfo){
//        //获取油企是否开启注册自动发券
//        log.info("获取油企是否开启注册自动发券：油企id：{}",appUserInfo.getStationId());
//        String couponActivity = couponService.getCouponActivity(appUserInfo.getStationId());
//        if (StringUtils.isNotBlank(couponActivity)){
//            log.info("获取发券方式：活动id：{}",couponActivity);
//            List<String> issueIdsByActivityId = couponService.getIssueIdsByActivityId(couponActivity);
//            if (CollectionUtil.isNotEmpty(issueIdsByActivityId)){
//                //调用发券接口
//                log.info("注册发券参数：{}，{}",appUserInfo.getMobilePhone(),issueIdsByActivityId);
//                couponController.registrationRelease(appUserInfo);
//            }
//        }
//        log.info("该油企没有注册发券活动");
//    }

    @PostMapping("/wx/addBonus")
    @ApiOperation(value = "微信同步卡包积分")
    public ResultData<String> wxAddBonus(@RequestBody WxAddBonus wxAddBonus) {
        weChatService.wxAddUserBonus(wxAddBonus);
        return ResultData.success("同步成功");
    }
}

